package com.jiang.starter.web.gzip;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.jiang.starter.web.util.GzipUtil;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Slf4j
@Aspect
@Component
public class GzipAspect {

    @Autowired
    private ObjectMapper objectMapper;

    @Around("@annotation(gzip)")
    public Object around(ProceedingJoinPoint joinPoint, Gzip gzip) throws Throwable {

        // 执行原方法获取返回数据
        Object result = joinPoint.proceed();

        // 查看请求头是否允许gzip
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = requestAttributes.getRequest();
        HttpServletResponse response = requestAttributes.getResponse();
        String acceptEncoding = request.getHeader("Accept-Encoding");

        // 如果允许则在响应头设置gzip
        if (acceptEncoding != null && acceptEncoding.contains("gzip")) {
            response.setHeader("Content-Encoding", "gzip");
        }

        // 使用gzip压缩并返回
        byte[] bytes = objectMapper.writeValueAsBytes(result);
        byte[] compressedBytes = GzipUtil.compress(bytes);
        response.getOutputStream().write(compressedBytes);
        return null;
    }

}
